<?php


if (!defined('MANS_'))
{
    die('Hacking attempt');
}


/**
 * 类
 */
class paypal
{
    /**
     * 构造函数
     *
     * @access  public
     * @param
     *
     * @return void
     */
   
    function __construct()
    {
     
    }

    /**
     * 生成支付代码
     * @param   array   $order  订单信息
     * @param   array   $payment    支付方式信息
     */
    function get_code($order)
    {
		
		$payment = $GLOBALS['Main']->paymentOne($order['pay_id']);
		
		$order_id = $order['order_id'];
		$order_sn = $order['order_sn'];
		$shipping_fee = $order['shipping_fee'];
		$discount = $order['discount'];
		
		$data_amount        = $order['order_amount'];
		
        $complete_url		= $GLOBALS['host']."/checkouts.php?act=payres&cd=paypal&o_id=$order_id";

        $account			= $payment['account'];
       
        $data_notify_url    = $GLOBALS['host'].'/checkouts.php?act=payres&cd=paypal';
        $cancel_return      = $GLOBALS['host'].'/cart';
		
		$addr = is_array($order['address']) ? $order['address']['address'] : $GLOBALS['Main']->json2Array(stripcslashes($order['address']));
	
	
		$city = $addr['city'];
		$country = $GLOBALS['db']->getOne("select `code` from region where region_name='".$addr['country_str']."'");
		$email = $addr['email'];
		$zip = $addr['zipcode'];
		
		$state = $addr['province_str'];
		$address1 = $addr['address'];
		
		
		$first_name  = $addr['user_name'];
		$last_name  = '';
		
		
		

        $def_url  = '<form name="pay_form" action="https://www.paypal.com/cgi-bin/webscr?locale.x=en_GB" method="post"  id="pay_form">' .   // 不能省略
            "<input type='hidden' name='cmd' value='_xclick'>" .                             // 不能省略
            "<input type='hidden' name='business' value='$account'>" .                 // 贝宝帐号
            "<input type='hidden' name='item_name' value='$order_sn'>" .                 // payment for
			//"<input type='hidden' name='shipping' value='$shipping_fee'>" .
			//"<input type='hidden' name='discount_amount' value='$discount'>" .
            "<input type='hidden' name='amount' value='$data_amount'>" .                        // 订单金额
            "<input type='hidden' name='currency_code' value='USD'>" .            // 货币
            "<input type='hidden' name='return' value='$complete_url'>" .                    // 付款后页面
            "<input type='hidden' name='invoice' value='$order_id'>" .                      // 订单号
            "<input type='hidden' name='charset' value='utf-8'>" .                              // 字符集
            "<input type='hidden' name='no_shipping' value='1'>" .                              // 不要求客户提供收货地址
            "<input type='hidden' name='no_note' value=''>" .                                  // 付款说明
            "<input type='hidden' name='notify_url' value='$data_notify_url'>" .
            "<input type='hidden' name='rm' value='2'>" .
            "<input type='hidden' name='cancel_return' value='$cancel_return'>" .
			//"<input type='hidden' name='city' value='$city'>" .
			//"<input type='hidden' name='country' value='$country'>" .
			//"<input type='hidden' name='state' value='$state'>" .
			//"<input type='hidden' name='address1' value='$address1'>" .
			//"<input type='hidden' name='first_name' value='$first_name'>" .
			//"<input type='hidden' name='last_name' value='$last_name'>" .
			//"<input type='hidden' name='zip' value='$zip'>" .
			
			 "<input type='submit' value=''  class='check_btn2'>" .                      // 按钮
            "</form>";
		
        return $def_url;
    }

    /**
     * 响应操作
     */
    function respond()
    {
		
        $payment        = $GLOBALS['Main']->paymentList();
		$payment        = $payment[0]; 
		
        $merchant_id    = $payment['account'];               ///获取商户编号
		
        // read the post from PayPal system and add 'cmd'
        $req = 'cmd=_notify-validate';
        foreach ($_POST as $key => $value)
        {
            $value = urlencode(stripslashes($value));
            $req .= "&$key=$value";
        }

        // post back to PayPal system to validate
        $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($req) ."\r\n\r\n";
        $fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);

        // assign posted variables to local variables
        $item_name = $_POST['item_name'];
        $item_number = $_POST['item_number'];
        $payment_status = $_POST['payment_status'];
        $payment_amount = $_POST['mc_gross'];
        $payment_currency = $_POST['mc_currency'];
        $txn_id = $_POST['txn_id'];
        $receiver_email = $_POST['receiver_email'];
        $payer_email = $_POST['payer_email'];
        $order_id = $_POST['invoice'];
       
		
        if (!$fp)
        {
            fclose($fp);

            return false;
        }
        else
        {
            fputs($fp, $header . $req);
			
            while (!feof($fp))
            {
                $res = fgets($fp, 1024);
				
				if (strcmp($res, 'VERIFIED') == 0)
                {
					
                    // check the payment_status is Completed
                    if ($payment_status != 'Completed' && $payment_status != 'Pending')
                    {
                        fclose($fp);

                        return false;
                    }
					
                    // check that receiver_email is your Primary PayPal email
                    if ($receiver_email != $merchant_id)
                    {
                        fclose($fp);

                        return false;
                    }
					
                    // check that payment_amount/payment_currency are correct
                    $sql = "SELECT order_amount FROM order_info WHERE order_id = '$order_id'";
				
                    if ($GLOBALS['db']->getOne($sql) != $payment_amount)
                    {
                        fclose($fp);

                        return false;
                    }
					
                    if ($payment['currency'] != $payment_currency)
                    {
                        fclose($fp);

                        return false;
                    }
					fclose($fp);

                    return true;
                }
                elseif (strcmp($res, 'INVALID') == 0)
                {
					
                    // log for manual investigation
                    fclose($fp);

                    return false;
                }
            }
			
        }
    }
}

?>